﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EPS.DataAccess;
using EPS.Contracts;

namespace EPS.Business
{
    public class ZoneService:IZone
    {
        private CommonService _commonService = null;

        public ZoneService()
        {
            _commonService = new CommonService();
        }

        public void Insert(EPS.Contracts.Zone zone)
        {
            zone.ZoneNo = GetMaxZoneNo(zone.ZoneNo);
            _commonService.InsertEntity(zone);
        }

        private string GetMaxZoneNo(string zoneNo)
        {
            if (zoneNo.Length == 3)
            {
                var max = _commonService.GetByLamda<Zone>(p => p.ZoneNo.Length == 3).Max(p => p.ZoneNo);
                if (!string.IsNullOrEmpty(max))
                {
                    return (int.Parse(max) + 1).ToString().PadLeft(3,'0');
                }
                else
                    return "001";
            }
            else
            {
                var max = _commonService.GetByLamda<Zone>(p => p.ZoneNo.Length == 6 && p.ZoneNo.StartsWith(zoneNo.Substring(0,3))).Max(p => p.ZoneNo);
                if (string.IsNullOrEmpty(max))
                {
                    return zoneNo.Substring(0, 3) + "001";
                }
                else
                {
                    return (int.Parse(max) + 1).ToString().PadLeft(6,'0');
                }
            }
        }

        public void Update(Zone zone)
        {
            _commonService.UpdateEntity<Zone>(zone);
        }

        public Zone GetById(string Keyid)
        {
            return _commonService.GetEntity<Zone>(p => p.Keyid == Keyid);
        }

        public List<Zone> GetBySql(string sql)
        {
            return _commonService.GetBySql<Zone>(sql);
        }

        public void DelById(string Keyid)
        {
            _commonService.DeleteEntity<Zone>(p => p.Keyid == Keyid);
        }
    }
}
